package com.bijava.taskjob;

import com.bijava.utils.LoggerFactoryUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.dataflow.DataflowJob;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyDataFlowJob implements DataflowJob {
    private static final Logger log = LoggerFactoryUtil.get();

    private static final ThreadLocal<Integer> LOOP_COUNTER = new ThreadLocal<>();
    //每次获取流处理循环次数
    private static final int LOOP_TIMES = 10;
    //计数器
    private static final AtomicInteger COUNTER = new AtomicInteger(1);


    private String getData(int shardingItem) {
        return shardingItem + "-" + COUNTER.getAndIncrement();
    }

    @Override
    public List fetchData(ShardingContext shardingContext) {
        Integer current = LOOP_COUNTER.get();
        if (current == null) {
            current = 1;
        } else {
            current += 1;
        }
        LOOP_COUNTER.set(current);
        if (current > LOOP_TIMES) {
            System.out.println("\n\n\n\n");
            return null;
        } else {
            int shardingItem = shardingContext.getShardingItem();
            List<String> datas = Arrays.asList(getData(shardingItem), getData(shardingItem), getData(shardingItem));
            return datas;
        }
    }

    @Override
    public void processData(ShardingContext shardingContext, List data) {
        LoggerFactoryUtil.info(log,"当前数据：{}",data);
        LoggerFactoryUtil.info(log,"当前线程：{}",Thread.currentThread().getId());
        LoggerFactoryUtil.info(log,"任务分片：{}",shardingContext.getShardingTotalCount());
        LoggerFactoryUtil.info(log,"当前分片：{}",shardingContext.getShardingItem());
        LoggerFactoryUtil.info(log,"分片参数：{}",shardingContext.getShardingParameter());
        LoggerFactoryUtil.info(log,"任务参数：{}",shardingContext.getJobParameter());
    }
}